//
//  ReportProjectDetailVC.m
//  efairy
//
//  Created by 李锋 on 2019/3/18.
//  Copyright © 2019年 East. All rights reserved.
//

#import "ReportProjectDetailVC.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "EFAModel.h"
#import <MJRefresh.h>
#import "ReportProjectDetailModel.h"
#import "ReportProjectDetailCell.h"
#import "ReportProjectDetail2Cell.h"
#import "ReportChartCell.h"
#import "ReportSearchCell.h"
#import "ReportDeviceAlarmListMoel.h"
#import "ReportDeviceAlarmPointCell.h"
#import "ReportProjectDeviceInfoModel.h"
#import "ReportDeviceVC.h"

@interface ReportProjectDetailVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIScrollViewDelegate>
//@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)ReportProjectDetailModel *model;
@property (nonatomic, strong) MJRefreshComponent * refreshViewComponent;
@property(nonatomic,strong)UITableView *tableView;
@property (nonatomic, assign) int pageIndex;
@property (nonatomic, assign) int totalRows;
@property(nonatomic,assign)BOOL isChooseChart;
@property(nonatomic,strong)NSMutableArray<DeviceAlarmInfoModel *> *deviceArray;
@property(nonatomic,strong)NSString *keyword;
@property (nonatomic,assign)float cellSearchViewY;
@property (nonatomic,strong)UIView *mSearchView;
@property (nonatomic,strong)UITextField *mTextField;


@end

@implementation ReportProjectDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _pageIndex = 1;
    _isChooseChart = YES;
    _keyword = @"";
    [self setNavigationBar];
    [self initview];
    [self queryReportProjectInfo];
    
}

-(void)setNavigationBar{
    self.navigationItem.title=@"项目报告详情";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"global_nav_back"] style:UIBarButtonItemStylePlain target:self action:@selector(backVC)];
}


- (void)backVC {
    //返回上一界面
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)initview{
    float barHeight =  self.navigationController.navigationBar.frame.size.height;
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, barHeight+statusBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT-barHeight-statusBarHeight)];
    _tableView.backgroundColor = ColorFromRGB(0xeff0f4);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//设置分割线为隐藏
    __weak  typeof(self) weakSelf = self;
//    //下拉刷新
//        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//            weakSelf.refreshViewComponent = weakSelf.tableView.mj_header;
//            weakSelf.pageIndex = 1;
////            [weakSelf queryReportProjectInfo:YES];
//        }];
    
    //上啦刷新
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.refreshViewComponent = weakSelf.tableView.mj_footer;
        weakSelf.pageIndex = weakSelf.pageIndex + 1;
//        [weakSelf queryReportProjectInfo:NO];
    }];
    
    _mSearchView = [[UIView alloc]initWithFrame:CGRectMake(0, statusBarHeight+barHeight, SCREEN_WIDTH, 40)];
    _mSearchView. backgroundColor = ColorFromRGB(0xffffff);
    _mSearchView.hidden = YES;
    
    //搜索栏背景
    UIView *searchBg =  [[UIView alloc]init];
    searchBg.layer.borderWidth=0.0f;
    searchBg.layer.cornerRadius=16.0f;
    searchBg.backgroundColor = ColorFromRGB(0xefefef);
    [_mSearchView addSubview:searchBg];
    
    //创建左侧搜索图标
    UIImageView *searchIcon=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 15, 15)];
    searchIcon.image=[UIImage imageNamed:@"search_icon"];
    [_mSearchView addSubview:searchIcon];
    
    //文本输入框
    _mTextField = [[UITextField alloc]init];
    _mTextField.backgroundColor = ColorFromRGB(0xefefef);
    _mTextField.clearButtonMode=UITextFieldViewModeAlways;//只要输入框有内容就出现
    // 设置提示文字
    _mTextField.placeholder = @"请输项目名称";
    _mTextField.layer.borderWidth=0.0f;
    _mTextField.layer.cornerRadius=16.0f;
    _mTextField.returnKeyType = UIReturnKeySearch;//变为搜索按钮
    _mTextField.delegate = self;//设置代理
    [_mSearchView addSubview:_mTextField];
    
    searchBg.sd_layout.heightIs(30)
    .topSpaceToView(_mSearchView, 5)
    .leftSpaceToView(_mSearchView, 16)
    .rightSpaceToView(_mSearchView, 16);
    
    searchIcon.sd_layout.heightIs(15)
    .widthIs(15)
    .topSpaceToView(_mSearchView, 12.5)
    .leftSpaceToView(_mSearchView, 32);
    
    _mTextField.sd_layout.heightIs(30)
    .topSpaceToView(_mSearchView, 5)
    .leftSpaceToView(searchIcon, 12)
    .rightSpaceToView(_mSearchView,16);
    
    [self.tableView.mj_footer resetNoMoreData];
    
//    [self.tableView.mj_header endRefreshing];
    [self.view sd_addSubviews:@[_tableView,_mSearchView]];
    
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(_cellSearchViewY > 0 && !_isChooseChart){
        if(scrollView.contentOffset.y >= _cellSearchViewY){
            if(_mSearchView.hidden){
                _mSearchView.hidden = NO;
            }
        }else if(scrollView.contentOffset.y < _cellSearchViewY){
            if(!_mSearchView.hidden){
                _mSearchView.hidden = YES;
            }
        }
    }
    
}

#pragma mark -UITextFieldDelegate
//搜索 这个函数是重写UITextFieldDelegate 当点击键盘搜索按钮触发
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    _keyword = self.mTextField.text;
    [_deviceArray removeAllObjects];
    [self.tableView reloadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self queryDeviceAlarmInfo:YES];
    });
                 
   
    return YES;
}


//颜值搜索栏输入的长度
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
    if (range.length == 1 && string.length == 0) {
        return YES;
    }else if (textField.text.length >= 30) {
        self.mTextField.text = [textField.text substringToIndex:30];
        return NO;
    }
    return YES;
}


//停止刷新头部或者底部
- (void)tableViewEndRefresh:(BOOL)isHeader {
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

#pragma UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(_isChooseChart){
        if(_model.efairyproject_device_alarm_statistics.device_alarm_statistics_list){
            return _model.efairyproject_device_alarm_statistics.device_alarm_statistics_list.count +2;
        }
    }else{
        if(_deviceArray){
            return _deviceArray.count +3;
        }
    }
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        ReportProjectDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"ReportProjectDetailCell" description]];
        if(!cell){
            cell = [[ReportProjectDetailCell alloc]init];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor whiteColor];
            cell.callPhoneBlock = ^{
                [self callSomeOneWithPhoneNum:_model.efairyproject_user_phonenumber];
            };
        }
        if(_model){
            [cell setDataModel:_model];
        }
        [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
        return cell;
    }else if(indexPath.section == 1){
        ReportProjectDetail2Cell *cell = [tableView dequeueReusableCellWithIdentifier:[@"ReportProjectDetail2Cell" description]];
        if(!cell){
            cell = [[ReportProjectDetail2Cell alloc]init];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.chooseChartReport = ^{
                _isChooseChart = YES;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                [self.tableView reloadData];
            };
            cell.chooseAlarmListReport = ^{
                _isChooseChart = NO;
                if(_deviceArray){
                    if(_deviceArray.count >= _totalRows){
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }else{
                        [self.tableView.mj_footer resetNoMoreData];
                    }
                    [self.tableView reloadData];
                }else{
                    [self queryDeviceAlarmInfo:YES];
                }
            };
        }
        cell.isChooseReportChartBtn = _isChooseChart;
        if(_model){
            [cell setDataModel:_model.efairyproject_device_statistics];
        }
        [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
        return cell;
        
    }
    if(_isChooseChart){
        ReportChartCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"ReportChartCell" description]];
        if(!cell){
            cell = [[ReportChartCell alloc]init];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor whiteColor];
            cell.layer.cornerRadius = 6;
            cell.layer.masksToBounds = YES;
        }
        if(_model.efairyproject_device_alarm_statistics){
            if(_model.efairyproject_device_alarm_statistics.device_alarm_statistics_list){
                     [cell configViewWithRptAlarmScaleItem: _model.efairyproject_device_alarm_statistics.device_alarm_statistics_list[indexPath.section-2]];
                
            }
        }
        [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
        return cell;
        
    }else{
        if(indexPath.section == 2){
            ReportSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"ReportSearchCell" description]];
            if(!cell){
                cell = [[ReportSearchCell alloc]init];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.backgroundColor = [UIColor whiteColor];
                cell.onClickSearchBtn = ^(NSString * _Nonnull text){
                    _keyword = text;
                    [self queryDeviceAlarmInfo:YES];
                };
                cell.onChangeTextField = ^(NSString * _Nonnull text) {
                    _keyword = text;
                };
            }
            [cell setkeyWord:_keyword];
            CGRect cellFrame = [tableView rectForSection:indexPath.section];
            _cellSearchViewY = cellFrame.origin.y;

            return cell;
        }else if(indexPath.section > 2){
            ReportDeviceAlarmPointCell *cell =  [tableView dequeueReusableCellWithIdentifier:[@"ReportDeviceAlarmPointCell" description]];
            if(!cell){
                cell = [[ReportDeviceAlarmPointCell alloc]init];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.backgroundColor = [UIColor whiteColor];
                cell.layer.cornerRadius = 6;
                cell.layer.masksToBounds = YES;
            }
           
            [cell setDataModel:_deviceArray[indexPath.section-3]];
            [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
            return cell;
        }
    }
    return nil;
    
}

#pragma UITableViewDelegate

////cell自适应高度设置
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:tableView];
}

//section header高度设置
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(_isChooseChart){
        if(section > 1){
            return 8.f;
        }
    }else{
        if(section > 2){
            return 8.f;
        }
    }

    return 0.0001;
}

//section footer高度设置
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}

//设置section中header的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc]init];
}

//设置sectin中footer的view
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc]init];
}

//点击cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(!_isChooseChart && _deviceArray){
        if(indexPath.section - 3 < _deviceArray.count){
            [self queryReportDeviceInfo:_deviceArray[indexPath.section-3].efairydevice_id];
        }
    }
}




//查询根据项目已生成的报表列表（每个设备的报警信息）
-(void)queryReportProjectInfo{
    
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    NSDictionary *params =  @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                              @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                              @"efairyreport_id":_reportId == nil ?@"":self.reportId,//报警id
                              @"efairyproject_id":_projectId,//项目编号
                              };
    
    NSLog(@"设备报表列表请求参数：%@",params);
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    [[XDAFNetworking sharedInstance]GET:[ApiManager apiReportProjectDetailInfo] parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task,id _Nullable responseObject){
        NSLog(@"获取的设备报表列表%@",responseObject);
        [hud hideAnimated:YES];
        _model=  [ReportProjectDetailModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask *_Nullable task,NSError * _Nullable error){
        NSLog(@"错误信息：%@",error);
        [hud hideAnimated:YES];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}


//查询设备报警列表信息
-(void)queryDeviceAlarmInfo:(BOOL)isHeader{
    
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    if(isHeader){
        _pageIndex = 1;
    }
    NSDictionary *params =  @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                              @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                              @"efairyreport_id":_reportId == nil ?@"":self.reportId,//报警id
                              @"efairyproject_id":_projectId,//项目编号
                              @"keyword":_keyword,
                              @"page":@(_pageIndex),
                              @"size":@"20"
                              };
    
    NSLog(@"设备报表列表请求参数：%@",params);
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    [[XDAFNetworking sharedInstance]GET:[ApiManager apiReportProjecDeviceList] parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task,id _Nullable responseObject){
        NSLog(@"获取的设备报表列表%@",responseObject);
        [hud hideAnimated:YES];
        [self tableViewEndRefresh:NO];
        ReportDeviceAlarmListMoel *model=  [ReportDeviceAlarmListMoel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        _totalRows = (int)model.total_rows;
        if( model.efairyproject_device_list){
            if(isHeader){
                _deviceArray = model.efairyproject_device_list;
            }else{
                if(_deviceArray){
                    [_deviceArray addObjectsFromArray:model.efairyproject_device_list];
                }
            }
            if(_deviceArray.count >= _totalRows){
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_footer resetNoMoreData];
            }
            
        }
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask *_Nullable task,NSError * _Nullable error){
        NSLog(@"错误信息：%@",error);
        [hud hideAnimated:YES];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}


//查询设备基本信息
-(void)queryReportDeviceInfo:(NSString *)deviceId{
    
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    NSDictionary *params =  @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                              @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                              @"efairyreport_id":_reportId == nil ?@"":self.reportId,//报警id
                              @"efairyproject_id":_projectId,//项目编号
                              @"efairydevice_id":deviceId//设备编号
                              };
    
    NSLog(@"设备信息请求参数：%@",params);
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    [[XDAFNetworking sharedInstance]GET:[ApiManager ApiReportProjectDeviceInfo] parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task,id _Nullable responseObject){
        NSLog(@"获取的设备信息%@",responseObject);
        [hud hideAnimated:YES];
        ReportProjectDeviceInfoModel *model=  [ReportProjectDeviceInfoModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        ReportDeviceVC *vc = [[ReportDeviceVC alloc]init];
        vc.reportId = _reportId;
        vc.projectId = _projectId;
        vc.deviceInfoMode = model;
        [self showViewController:vc sender:nil];
        
    } failure:^(NSURLSessionDataTask *_Nullable task,NSError * _Nullable error){
        NSLog(@"错误信息：%@",error);
        [hud hideAnimated:YES];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}


//根基手机号自动跳到打电话页面
- (void)callSomeOneWithPhoneNum:(NSString*)phoneNum {
    NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@",phoneNum];
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }
}


@end
